<template>
    <div class="charts-container">
        <div class="search-content">
            <el-form :model="searchContent" ref="searchFrom" :inline="true">
                <el-form-item label="日期：">
                    <el-date-picker
                        v-model="dateInterval"
                        type="daterange"
                        :clearable="false"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"
                        @focus="handleDateFocus"
                        @change="handleChangeDate">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="商家名称：">
                    <el-select
                        v-model="searchContent.store_id"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        autocomplete
                        placeholder="选择店铺、搜索店铺"
                        :remote-method="handleStoreInput"
                        :loading="loading"
                        @focus="handleStore">
                        <el-option
                            v-for="item in storeLists"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属品线：">
                    <el-select v-model="searchContent.depart_id" @change='handleDepartChange' placeholder="全部" clearable>
                        <el-option
                            v-for="item in departType"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="charts-box" style="margin-top: 7px;">
            <div class="charts-header">
                <div class="charts-title">
                    企微互动客户数
                    <el-tooltip effect="dark" content="员工主动发送过消息的单聊总客户人数" placement="top"><i class="el-icon-question"></i></el-tooltip>
                </div>
            </div>
            <div class="charts-content">
                <charts :dataArr="dataArr" :showParticleSize="showParticleSize" container="c1" :hasType="false"></charts>
            </div>
        </div>
        <div class="charts-box">
            <div class="charts-header">
                <div class="charts-title">企微互动客户数明细</div>
            </div>
            <div class="charts-content" style="padding-top: 0;">
                <Lists :searchContent="searchContents"/>
            </div>
        </div>
    </div>
</template>
<script>
import datePicker from '../datePicker.vue';
import charts from '../charts.vue';
import Lists from './interaction-lists.vue';
import { dateFormatter } from '@/common/js/util'
export default {
    data() {
        return {
            showParticleSize: false,
            searchContent: {},         // 搜索字段
            searchContents: {},        // 列表搜索字段
            dateInterval: [],          // 默认日期
            departType: [],            // 品线类型数组
            storeLists: [],            // 店铺数据
            loading: false,            // 店铺加载动画
            dataArr: {
                labelFormat: 'MM-DD',
                tooltip: {
                    valueSuffix: ' 人'
                },
                series:  []
            },
            pickerMinDate: null,
            pickerOptions: {
                onPick: ({ maxDate, minDate }) => {
                    this.pickerMinDate = minDate
                },
                disabledDate: time => {
                    if(!this.pickerMinDate) return time.getTime() > Date.now() - 8.64e7 // 必须选择一个日期后才开始按照29天的规则
                    const intervalTtime = 29 * 24 * 3600 * 1000; // 仅支持选择29天范围
                    const currDate = this.pickerMinDate ? new Date(this.pickerMinDate) : new Date()
                    const minTime = currDate.getTime() - intervalTtime;
                    const maxTime = currDate.getTime() + intervalTtime;
                    let date = new Date(), dateTime = Date.now(), nowMonth = true;
                    // nowMonth = time.getFullYear() <= date.getFullYear() && time.getMonth() < date.getMonth(); // 不支持当月
                    dateTime -= 8.64e7; // 不支持当日
                    return time.getTime() > dateTime || time.getTime() < minTime || time.getTime() > maxTime || !nowMonth
                }
            }
        }
    },
    components: { datePicker, charts, Lists },
    methods: {
        handleChangeDate(val) {
            if(val) {
                this.searchContent.begin_date = val[0];
                this.searchContent.end_date = val[1];
            } else {
                this.searchContent.begin_date = null;
                this.searchContent.end_date = null;
            }
        },
        // 店铺请求
        handleStore(){
            this.getStoreList();
        },
        // 店铺搜索
        handleStoreInput(keywords) {
            this.getStoreList(keywords);
        },
        // 获取店铺列表数据
        getStoreList(storeName = '', store_id_in = null) {
            this.loading = true
            const data = {
                page: 1,
                eachNum: 200,
                storeName,
                loadingclose: false,
                storeUserName: '',
                type: 'filter_not_yt'
            };
            if(store_id_in) {
                data.store_id_in = store_id_in
            }
            this.$http.post('/admin/store/index.php?act=storeManage&op=getStoreList', data).then(res => {
                this.loading = false
                if (res.code == 1) {
                    this.storeLists = res.data && res.data.list && 
                    res.data.list.map(item => ({
                        value: item.store_id,
                        label: item.store_name
                    })) || []
                } else {
                    this.storeLists = [];
                    res.msg && this.$message.error(res.msg)
                }
            })
        },
        // 获取品线数据
        handleDepart() {
            this.$http.post("/admin/depart/index.php?act=departManage&op=groupList", {depart_id: 600}) // 600 为集团ID
            .then( res => {
                if (res.code == 1 && res.data.length > 0) {
                    this.departType = res.data.map(item =>({
                        depart_id: item.depart_id,
                        store_ids: item.store_ids,
                        label: item.depart_name, 
                        value: item.depart_id
                    }));
                } else {
                    this.$message.error("品线数据获取失败!")
                }
            })
        },
        // 品线选择
        handleDepartChange(val) {
            const depart = this.departType.find(depart => depart.depart_id == val)
            this.searchContent.store_id_in = depart.store_ids.join(",")
        },
        handleSearch() {
            this.getChartData()
        },
        handleReset() {
            this.handleDateFocus()
            this.init()
        },
        handleDateFocus() {
            this.pickerMinDate = null
        },
        // 获取客户互动人数
        getChartData() {
            let datas = this.searchContent;
            this.searchContents = {...datas}
            /*this.$http.get('/admin/store/index.php?act=followUser&op=chatCnt', {params: datas})
            .then(res => {
                if(res.code == 1) {
                    this.dataArr.series = [{
                        name: '互动人数',
                        color: '#FF5A5A',
		                data: res.data.map(item => ([item.stat_time, parseFloat(item.chat_cnts)])) || [],
                    }];
                }
            })*/
            this.$http.get('/admin/yt_car/index.php?act=statistic&op=getEnterpriseWechatInteractStatistics', {params: datas})
            .then(res => {
                if(res.code == 1) {
                    this.dataArr.series = [{
                        name: '互动人数',
                        color: '#FF5A5A',
		                data: res.data || [],
                    }];
                }
            })
        },
        init() {
            // 取最近30天日期(不含当天)
            const date = new Date()
            date.setDate(date.getDate() - 1)
            const end = dateFormatter("YYYY-MM-DD", date.getTime())
            date.setDate(date.getDate() - 29)
            const begin = dateFormatter("YYYY-MM-DD", date.getTime())
            this.dateInterval = [begin, end]

            // 默认搜索属性
            this.searchContent = {
                data_type: 0,         // 类型
                begin_date: begin,    // 开始时间
                end_date: end,        // 结束时间 
                store_id: '',         // 店铺ID
                store_name: '',       // 店铺名称
                depart_id: '',        // 品线ID
                store_id_in: ''       // 店铺ID字符串集合
            }
            this.storeLists = []      // 店铺列表
            this.getChartData()
        }
    },
    mounted() {
        this.init()
        this.handleDepart()
    }
}
</script>
<style scoped lang="scss">
    @import url('~@/common/scss/charts-public.scss');
    .charts-container {
        box-shadow: none;
        width: calc(100% + 10px);
        height: calc(100% - 29px);
        margin: 0 -5px;
        .el-tooltip {
            color: #bbb;
            font-size: 16px;
            cursor: pointer;
            vertical-align: -1px;
            display: none;
        }
    }
    .search-content { padding: 7px 0 0 0; }
    .charts-box {
        background: #fff;
        box-shadow: 0px 0px 10px #ddd;
        box-sizing: border-box;
        height: calc(50% - 52px);
        margin: 15px 5px 2px;
        position: relative;
        flex-grow: 1;
        &:last-child {
            height: calc(50% - 40px)
        }
        .charts-more {
            top: 11px;
        }
        .charts-content {
            padding-top: 10px;
            /deep/ .chart-content { padding-bottom: 10px;}
        }
    }
</style>